<template>
  <div class="the-map-component">
    <v-stage ref="ref-stage" :config="stageConfig">
      <v-layer>
        <v-image
          :config="{
          image:mapImage,
          width:mapSize,
          height:mapSize,
          opacity:0.7
        }"
        ></v-image>
        <!-- <v-rect
          :config="{
          x: 0,
          y: 0,
          width: 100,
          height: 100,
          fill: 'red',
          shadowBlur: 10
        }"
        />-->
      </v-layer>
      <v-layer ref="lines-layer"></v-layer>
    </v-stage>
    <hr />
    <br />
    <!-- <event-time></event-time> -->
  </div>
</template>

<script>
import axios from "axios";
import konva from "konva";
import { map, clamp, sortBy } from "lodash";
import EventTime from "./EventTime";

// const KonvaLayer = konva.Layer;
const DesertMap_VictimsDistribution_102M =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/E9/0D/Cii-TF7zm_iIMiciAAERNXXTYs8AANTQwNmT9kAARFN18.json";
const SavageMap_VictimsDistribution_102M =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/E9/14/Cii-U17zt_yIX0LdAABD5-Wcp_wAANTVANsWToAAEP_48.json";
const SavageMap_VictimsDistribution_51M =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/E9/14/Cii-U17zt5qIFN-hAADpdnroWacAANTVANh3mYAAOmO16.json";
const DihorOtokMap_VictimsDistribution_7650cm =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/E9/14/Cii-TF7zuSaITwoEAAConm2Oz4UAANTVQOyyZgAAKi282.json";
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "http://p1-q.mafengwo.net/s16/M00/25/2E/CoUBUl6J8HWAB3mbABe2H5mDyy8107.jpg#Savage_Main.jpg.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};

const MAP_NAME = "Miramar";

const toScale = (pubgMapSize, mapSize, n) =>
  (n / pubgMapSize) * mapSize * (pubgMapSize === 816000 ? 0.99609375 : 1);

const DRAW_MAP_SIZE = 1050;
export default {
  name: "HelloWorld",
  data() {
    return {
      mapSize: DRAW_MAP_SIZE,
      stageConfig: {
        width: DRAW_MAP_SIZE,
        height: DRAW_MAP_SIZE,
        draggable: true
      },
      mapName: MAP_NAME,
      mapImageLink: MAP_IMAGES[MAP_NAME],
      mapImage: (_ => {
        let img = new window.Image();
        img.src = MAP_IMAGES[MAP_NAME];
        return img;
      })(),
      mapScale: 1,
      offsetX: 0,
      offsetY: 0
    };
  },
  computed: {},
  components: {
    EventTime
  },
  async mounted() {
    let grids_data = await this.getRemoteData(DesertMap_VictimsDistribution_102M);
    let mapSize = DRAW_MAP_SIZE;
    const GRID_WIDTH_Centimeter = 10200;
    let rawMapSize = MAP_LENGTH_CENTIMETERS[MAP_NAME];
    const _scale = mapSize / rawMapSize;
    let konva_grids = (() => {
      let rects = [];
      let VictimColorMapFunc = val => {
        if (val === 0) {
          return "rgba(0,0,0,0)"; //透明
        }
        if (val <= 0.01) {
          return "rgba(132,196,118,0.3)"; //绿色
        }
        if (val > 0.01 && val < 0.1) {
          return "rgba(214,221,65,0.5)"; //变黄
        }
        if (val >= 0.1 && val < 0.5) {
          return "rgba(238,90,12,0.7)"; //橘色
        }
        if (val >= 0.5 && val < 1) {
          return "rgba(255,0,0,0.8)"; //变红
        }
        if (val >= 1) {
          return "rgba(102,0,102,0.8)"; //紫色
        }
      };
      let VictimColorMapFunc_xuedi = val => {
        if (val === 0) {
          return "rgba(0,0,0,0)"; //透明
        }
        if (val <= 0.02) {
          return "rgba(132,196,118,0.3)"; //绿色
        }
        if (val > 0.02 && val < 0.1) {
          return "rgba(214,221,65,0.5)"; //变黄
        }
        if (val >= 0.1 && val < 0.5) {
          return "rgba(238,90,12,0.7)"; //橘色
        }
        if (val >= 0.5 && val < 1) {
          return "rgba(255,0,0,0.8)"; //变红
        }
        if (val >= 1) {
          return "rgba(153,0,0,0.8)"; //深红
        }
      };
      for (let xi = 0; xi < grids_data.length; xi++) {
        for (let yi = 0; yi < grids_data[xi].length; yi++) {
          if (grids_data[xi][yi] > 0) {
            // console.log(xi, yi, grids_data[xi][yi]);
            let [x, y, width] = [
              xi * GRID_WIDTH_Centimeter,
              yi * GRID_WIDTH_Centimeter,
              GRID_WIDTH_Centimeter
            ].map(e => e * _scale);
            // debugger
            let rect = new konva.Rect({
              x: x,
              y: y,
              width: width,
              height: width,
              fill: VictimColorMapFunc_xuedi(grids_data[xi][yi]),
              stroke: "rgba(0,0,0,1)",
              strokeWidth: 0.05
              // opacity:0.5||grids_data[xi][yi]
            });
            rects.push(rect);
          }
        }
      }
      return rects;
    })();
    // debugger;

    // return;

    // debugger
    let v_layer = this.$refs["lines-layer"];
    /**@type {konva.Layer} */
    let layer = v_layer.getNode();
    layer.add(...konva_grids);
    // var rect1 = new Konva.Rect({
    //   x: 20,
    //   y: 20,
    //   width: 100,
    //   height: 50,
    //   fill: "green",
    //   stroke: "black",
    //   strokeWidth: 4
    // });
    // layer.add(rect1);
    // layer.add(...killer_points);
    // layer.add(...victim_points);
    // layer.add(...arrows);
    // layer.add(...zoneCircles);
    layer.draw();

    const MIN_SCALE = 1;
    const MAX_SCALE = 50;
    let v_stage = this.$refs["ref-stage"];
    /**@type {konva.Stage} */
    let stage = v_stage.getNode();
    let v = this;

    let handleZoom =
      /**
       * @param {Number} scaleDelta
       * @param {Number} layerX?
       * @param {Number} layerY?
       */
      (scaleDelta, layerX, layerY) => {
        if (!layerX) layerX = DRAW_MAP_SIZE / 2;
        if (!layerY) layerY = DRAW_MAP_SIZE / 2;
        let newScale = clamp(v.mapScale * scaleDelta, MIN_SCALE, MAX_SCALE);
        let mousePointX = layerX / v.mapScale - v.offsetX / v.mapScale;
        let mousePointY = layerY / v.mapScale - v.offsetY / v.mapScale;
        let offsetX = -(mousePointX - layerX / newScale) * newScale;
        let offsetY = -(mousePointY - layerY / newScale) * newScale;
        offsetX = clamp(offsetX, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        offsetY = clamp(offsetY, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        // debugger
        v.mapScale = newScale;
        v.offsetX = offsetX;
        v.offsetY = offsetY;
        // debugger;
        stage.scaleX(newScale);
        stage.scaleY(newScale);
        stage.x(offsetX);
        stage.y(offsetY);
        stage.batchDraw();
      };
    stage.dragBoundFunc(pos => {
      // debugger;
      let { x, y } = pos;
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      return {
        x,
        y
      };
    });
    stage.on("dragend", ev => {
      // debugger
      let x = ev.target.x();
      let y = ev.target.y();
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      stage.x(x);
      stage.y(y);
      stage.batchDraw();
    });
    stage.on("wheel", ev => {
      console.log(ev);
      ev.evt.preventDefault();
      const scaleDelta = ev.evt.deltaY > 0 ? 1 / 1.2 : 1.2;
      handleZoom(scaleDelta, ev.evt.layerX, ev.evt.layerY);
    });
    // debugger;
  },
  methods: {
    getRemoteData(link) {
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@mapSize: 800px;
.the-map-component {
  // display: flex;
  #map {
    width: @mapSize;
    height: @mapSize;
  }
  .h-check-players {
  }
}
</style>
